import React, { useState, useEffect } from 'react';
import * as XLSX from 'xlsx';
import { Table, Space, Button, Popconfirm, message, Tooltip, Modal, Form, Input, Upload } from 'antd';
import { EditOutlined, DeleteOutlined, EyeOutlined, SearchOutlined, UploadOutlined, DownloadOutlined } from '@ant-design/icons';
import importedFieldMapping from '../config/field-mapping.json';

// 默认字段映射配置 - 当配置文件无效时使用
const DEFAULT_FIELD_MAPPINGS = [
  { englishField: 'YEAR', chineseName: '年份' },
  { englishField: 'MONTH', chineseName: '月份' },
  { englishField: 'BMMS2', chineseName: '二级部门' },
  { englishField: 'BMMS3', chineseName: '三级部门' }
];

// 详细验证配置文件加载和结构
let fieldMapping = importedFieldMapping;
if (!fieldMapping) {
  console.error('错误: 字段映射配置文件未找到，使用默认配置');
  message.warning('字段映射配置文件未找到，使用默认配置');
  fieldMapping = DEFAULT_FIELD_MAPPINGS;
} else if (!Array.isArray(fieldMapping)) {
  console.error('错误: 字段映射配置不是数组格式，使用默认配置');
  message.error('字段映射配置格式错误，使用默认配置');
  fieldMapping = DEFAULT_FIELD_MAPPINGS;
} else if (fieldMapping.length === 0) {
  console.warn('警告: 字段映射配置为空数组，使用默认配置');
  message.warning('字段映射配置为空，使用默认配置');
  fieldMapping = DEFAULT_FIELD_MAPPINGS;
} else {
  // 检查第一个配置项的结构
  const firstItem = fieldMapping[0];
  if (!firstItem || typeof firstItem !== 'object' || !firstItem.englishField || !firstItem.chineseName) {
    console.error('错误: 字段映射配置结构不正确，使用默认配置');
    message.error('字段映射配置结构错误，使用默认配置');
    fieldMapping = DEFAULT_FIELD_MAPPINGS;
  }
}
console.log('从../config/field-mapping.json导入的配置:', importedFieldMapping, '长度:', importedFieldMapping.length);


const DataTable = ({ data }) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [editingRecord, setEditingRecord] = useState(null);
  const [searchText, setSearchText] = useState('');
  const [filteredData, setFilteredData] = useState([]);

  // 组件挂载时初始化数据
  useEffect(() => {
    console.log('组件接收的数据:', data);
    // 处理可能的嵌套数据结构
    const tablesData = Array.isArray(data) ? data : (data?.tables || data?.data || []);
    setFilteredData(tablesData);
  }, [data]);

  const showModal = (record) => {
    setEditingRecord(record);
    form.setFieldsValue({
      chineseName: record['中文名称'] || '',
      englishName: record['英文名称'] || '',
    });
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 搜索功能
  const handleSearch = (e) => {
    const value = e.target.value;
    setSearchText(value);
    setFilteredData(
      data.filter(item => 
        item['中文名称']?.includes(value) || item['英文名称']?.includes(value)
      )
    );
  };

  // 导入Excel处理
  const handleImport = (file) => {
    const reader = new FileReader();
    reader.onload = (e) => {
      try {
        const workbook = XLSX.read(e.target.result, { type: 'array' });
        // 遍历所有sheet
        workbook.SheetNames.forEach(sheetName => {
          // 解析sheet名称格式：中文表名-英文表名
          const [chineseName, englishName] = sheetName.split('-');
          if (!chineseName || !englishName) {
            message.warning(`Sheet名称格式错误: ${sheetName}，应为"中文表名-英文表名"`);
            return;
          }

          // 读取sheet数据
          const worksheet = workbook.Sheets[sheetName];
          // 解析并规范化表头（移除特殊字符和空格）
          const jsonData = XLSX.utils.sheet_to_json(worksheet);
          const normalizeHeader = (header) => {
            // 移除所有非字母数字和中文字符
            return header.replace(/[^一-龥a-zA-Z0-9]/g, '').trim();
          };
          const normalizedData = jsonData.map(item => {
            const normalizedItem = {};
            Object.keys(item).forEach(key => {
              const normalizedKey = normalizeHeader(key);
              normalizedItem[normalizedKey] = item[key];
            });
            return normalizedItem;
          });

          // 验证是否有数据
          if (normalizedData.length === 0) {
            message.warning(`Sheet ${sheetName} 没有可导入的数据`);
            return;
          }

          // 验证数据格式是否包含中文字段和英文字段
          if (normalizedData.length > 0) {
            const firstRow = normalizedData[0];
            const hasChineseField = Object.keys(firstRow).some(key => key.includes('中文'));
            const hasEnglishField = Object.keys(firstRow).some(key => key.includes('英文'));
            if (!hasChineseField || !hasEnglishField) {
              message.warning(`Sheet ${sheetName} 缺少中文字段或英文字段列`);
              return;
            }
          }

          // 使用配置文件动态映射Excel列到后端字段格式
          console.log('字段映射配置:', fieldMapping);
          console.log('处理前的数据示例:', normalizedData.slice(0, 3));
          
          
          const mappedData = normalizedData.map((item, index) => {
            const mappedItem = {};
            const missingFields = [];
            
            fieldMapping.forEach(mapping => {
            Object.keys(mapping).forEach(key => {
              const possibleHeaders = mapping[key];
              let found = false;
              
              for (const header of possibleHeaders) {
                const normalizedConfigHeader = normalizeHeader(header);
                if (item.hasOwnProperty(normalizedConfigHeader)) {
                  mappedItem[key] = item[normalizedConfigHeader]?.trim();
                  found = true;
                  break;
                }
              }
              
              if (!found) {
                missingFields.push(key);
              }
            });
          });
            
            // 记录映射问题以便调试
            if (missingFields.length > 0) {
              console.log(`行${index+1}缺少字段:`, missingFields, '数据:', item);
            }
            return mappedItem;
          });
          
          // 验证映射结果
          const invalidItems = mappedData.filter(item => !item.englishField || !item.chineseName);
          
          if (invalidItems.length > 0) {
            message.warning(`发现${invalidItems.length}条无效数据，缺少必要字段`);
            console.warn('无效数据示例:', invalidItems.slice(0, 3));
          } else if (mappedData.length > 0) {
            console.log('数据映射成功示例:', mappedData.slice(0, 3));
          }

          // 发送数据到后端保存
          console.log('发送到后端的数据:', { chineseName, englishName, data: mappedData });
          fetch('/api/tables/import', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ 
              chineseName,
              englishName,
              data: mappedData.map(item => ({ 
                englishField: item.englishField || '', 
                chineseName: item.chineseName || '' 
              }))
            })
          })
          .then(res => res.json())
          .then(() => {
            message.success(`成功导入表: ${chineseName}`);
            window.location.reload();
          })
          .catch(err => {
            message.error(`导入表 ${chineseName} 失败: ${err.message || '未知错误'}`);
          });
        });
      } catch (err) {
        message.error('Excel解析失败: ' + err.message);
      }
    };
    reader.readAsArrayBuffer(file);
    return false; // 阻止默认上传行为
  };

  // 导出Excel处理 - 简化版
  const handleExport = () => {
    debugger;
    console.log('导出按钮被点击');
    try {
      // 验证数据是否存在
      if (!Array.isArray(filteredData) || filteredData.length === 0) {
        message.warning('没有可导出的数据');
        return;
      }

      // 准备导出数据 - 仅包含中英文两列
      const exportData = filteredData.map(record => ({
        '英文字段': record.englishField || 'N/A',
        '中文字段': record.chineseName || 'N/A'
      }));

      // 创建工作簿和工作表
      const workbook = XLSX.utils.book_new();
      const worksheet = XLSX.utils.json_to_sheet(exportData);
      XLSX.utils.book_append_sheet(workbook, worksheet, '字段映射');

      // 保存文件
      XLSX.writeFile(workbook, '数据字典导出.xlsx');
      message.success('导出成功');
      console.log('导出成功，共', exportData.length, '条记录');
    } catch (error) {
      console.error('导出过程出错:', error);
      message.error(`导出失败: ${error.message || '未知错误'}`);
    }
  };


  const handleSave = () => {
    form.validateFields()
      .then(values => {
        const updateData = {
          newChineseName: values.chineseName,
          newEnglishName: values.englishName
        };
        
        fetch(`/api/tables/${editingRecord['英文名称']}`, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(updateData),
        })
        .then(response => {
          if (!response.ok) {
            return response.json().then(data => {
              throw new Error(data.error || '更新表名称失败');
            });
          }
          return response.json();
        })
        .then(data => {
          message.success('表名称已更新');
          setIsModalVisible(false);
          // 刷新父组件数据
          window.location.reload();
        })
        .catch(error => {
          message.error(error.message);
          console.error('更新失败:', error);
        });
      })
      .catch(info => {
        console.error('表单验证失败:', info);
      });
  };

  // 处理空数据情况
  if (filteredData.length === 0) {
    return (
      <div style={{
        textAlign: 'center',
        padding: '60px 20px',
        backgroundColor: '#f9f9f9',
        borderRadius: 8,
        border: '1px dashed #e8e8e8'
      }}>
        <EyeOutlined style={{ fontSize: '48px', color: '#ccc', marginBottom: 16 }} />
        <h3 style={{ color: '#666', margin: 0 }}>暂无数据</h3>
        <p style={{ color: '#999', maxWidth: '300px', margin: '10px auto' }}>请导入Excel文件以查看数据</p>
      </div>
    );
  }

  const columns = [
  {
    title: (
      <Tooltip title="中文名称">
        中文名称
      </Tooltip>
    ),
    dataIndex: 'chineseName',
    key: 'chineseName',
    sorter: (a, b) => {
      if (typeof a['chineseName'] === 'string' && typeof b['chineseName'] === 'string') {
        return a['chineseName'].localeCompare(b['chineseName']);
      }
      return a['chineseName'] - b['chineseName'];
    },
    render: text => (
      <div style={{
        maxWidth: 300,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        cursor: 'pointer',
        transition: 'all 0.3s'
      }} title={text}>
        {text}
      </div>
    ),
  },
  {
    title: (
      <Tooltip title="英文名称">
        英文名称
      </Tooltip>
    ),
    dataIndex: 'englishField',
    key: 'englishField',
    sorter: (a, b) => {
      if (typeof a['englishField'] === 'string' && typeof b['englishField'] === 'string') {
        return a['englishField'].localeCompare(b['englishField']);
      }
      return a['englishField'] - b['englishField'];
    },
    render: text => (
      <div style={{
        maxWidth: 300,
        whiteSpace: 'nowrap',
        overflow: 'hidden',
        textOverflow: 'ellipsis',
        cursor: 'pointer',
        transition: 'all 0.3s'
      }} title={text}>
        {text}
      </div>
    ),
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    render: (_, record) => (
      <Space size="small">
        <Button
          type="text"
          icon={<EditOutlined />}
          size="small"
          onClick={() => showModal(record)}
          style={{ color: '#1890ff' }}
        >
          编辑名称
        </Button>
        <Popconfirm
          title="确定要删除这条数据吗?"
          onConfirm={() => message.success('删除成功')}
          okText="是"
          cancelText="否"
        >
          <Button
            type="text"
            icon={<DeleteOutlined />}
            size="small"
            style={{ color: '#ff4d4f' }}
          />
        </Popconfirm>
      </Space>
    ),
  }
]

  return (
    <div style={{ padding: '16px' }}>
      {/* 搜索和导入导出工具栏 */}
      <div style={{ marginBottom: '16px', display: 'flex', alignItems: 'center', gap: '16px' }}>
        {/* 导入导出按钮 */}
        <div style={{ display: 'flex', gap: '8px' }}>
          <Upload
            name="file"
            beforeUpload={handleImport}
            showUploadList={false}
          >
            <Button type="primary" icon={<UploadOutlined />}>
              导入Excel
            </Button>
          </Upload>
          <Button icon={<DownloadOutlined />} onClick={handleExport}>
            导出Excel
          </Button>
        </div>
        {/* 搜索框 */}
        <div style={{ flexGrow: 1 }}>
          <Input
            placeholder="搜索表名"
            value={searchText}
            onChange={handleSearch}
            prefix={<SearchOutlined />}
            style={{ width: 300 }}
          />
        </div>
      </div>

      <div>
        <Table
          columns={columns}
          dataSource={filteredData.map((item, index) => ({ ...item, key: index }))}
          pagination={{
            pageSize: 10,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '50'],
            showTotal: (total) => `共 ${total} 条数据`
          }}
          bordered
          scroll={{ x: 'max-content' }}
          size="middle"
          tableLayout="fixed"
          style={{
            borderRadius: 8,
            overflow: 'hidden',
            boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
          }}
        />
      </div>

      <Modal
        title="编辑表名称"
        visible={isModalVisible}
        onCancel={handleCancel}
        footer={[
          <Button key="cancel" onClick={handleCancel}>取消</Button>,
          <Button key="save" type="primary" onClick={handleSave}>保存</Button>,
        ]}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="chineseName"
            label="中文名称"
            rules={[{ required: true, message: '请输入中文名称' }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            name="englishName"
            label="英文名称"
            rules={[{ required: true, message: '请输入英文名称' }]}
          >
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
};

export default DataTable;